package mq

import (
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"gitee.com/zhongguo168a/gocodes/myx/pool"
	"github.com/nsqio/go-nsq"
)

var producers = pool.NewPoolMap()

func GetProducer(address string) (producer *Producer, err error) {
	if producers.Count(address) == 0 {
		nsqproducer, newerr := nsq.NewProducer(address, nsq.NewConfig())
		if newerr != nil {
			err = errorx.Wrap(newerr, "nsq.NewProducer", datax.M{"address": address})
			return
		}
		err = nsqproducer.Ping()
		if err != nil {
			err = errorx.Wrap(err, "producer.Ping", datax.M{"address": address})
			return
		}

		producer = &Producer{}
		producer.Producer = nsqproducer
		return
	}

	producer = producers.Get(address).(*Producer)
	return
}

type Producer struct {
	*nsq.Producer
}

// Close 返回池中
func (producer *Producer) Close() {
	producers.Put(producer.String(), producer)
}
